﻿namespace LogManager.TestUtility
{
    using System.IO;
    using System.Security.AccessControl;
    using System.Security.Principal;

    public class RightsManager
    {
        public static void RemoveUserAffectations(string path, NTAccount account)
        {
            SecurityIdentifier sid = (SecurityIdentifier)account.Translate(typeof(SecurityIdentifier));

            var security = Directory.GetAccessControl(path);
            var rules = security.GetAccessRules(true, true, typeof(NTAccount));

            foreach (FileSystemAccessRule rule in rules)
            {
                if (rule.IdentityReference.Value == account.Value)
                    security.RemoveAccessRuleSpecific(rule);
            }
            Directory.SetAccessControl(path, security);
        }

        public static void SetAccess(string path, NTAccount account, AccessControlType acl)
        {
            RemoveUserAffectations(path, account);

            SecurityIdentifier sid = (SecurityIdentifier)account.Translate(typeof(SecurityIdentifier));

            var rights = FileSystemRights.Modify | FileSystemRights.Read | FileSystemRights.Write | FileSystemRights.ListDirectory | FileSystemRights.Delete;

            // Create the rules
            FileSystemAccessRule writerule = new FileSystemAccessRule(sid, rights, acl);

            // Get your file's ACL
            DirectorySecurity fsecurity = Directory.GetAccessControl(path);

            // Add the new rule to the ACL
            fsecurity.AddAccessRule(writerule);

            // Set the ACL back to the file
            Directory.SetAccessControl(path, fsecurity);
        }
    }
}
